import { FC, useEffect, useState } from 'react'
import { Dialog, ImageUploader, Toast } from 'antd-mobile'
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader'
import { FileService } from '../../services'
import { Warnicon, Winicon } from '../Icon'

interface Props {
  onChange: (value: string[]) => void
  max: number
  url?: string
  value?: string[]
}

const LimitCount: FC<Props> = ({ onChange, max, url, value }) => {
  const maxCount = 6
  const [fileList, setFileList] = useState<ImageUploadItem[]>([])

  useEffect(() => {
    async function getData() {
      setFileList([{ url: url as string }])
    }
    if (url && url !== '') getData()
  }, [url])

  useEffect(() => {
    if (value) {
      const imgs: ImageUploadItem[] = value.map(item => { return { url: item } })
      setFileList(imgs)
    }
  }, [value])

  function beforeUpload(file: File) {
    if (file.size > 1024 * 1024) {
      Toast.show('请选择小于 1M 的图片')
      return null
    }
    return file
  }

  return (
    <ImageUploader
      value={fileList}
      onChange={(items) => {
        setFileList(items)
        onChange(items.flatMap(url => url.url) as string[])
      }}
      upload={async (file: File) => {
        const data = new FormData()
        data.append('file', file as File)
        const res = await FileService.upload(data)
        if (res.stat === 'OK') {
          Toast.show({ content: <Winicon text='图片上传成功' /> })
          return { url: res.url }
        } else Toast.show({ content: <Warnicon text='图片上传失败' /> })
        return {
          url: URL.createObjectURL(file),
        }
      }}
      multiple
      maxCount={max}
      showUpload={fileList.length < maxCount}
      onCountExceed={exceed => {
        Toast.show(`最多选择 ${maxCount} 张图片，你多选了 ${exceed} 张`)
      }}
      onDelete={() => {
        return Dialog.confirm({
          content: '是否确认删除',
        })
      }}
      beforeUpload={beforeUpload}
    />
  )
}

export default LimitCount

